//
//  YQQRCode.m
//  youqu
//
//  Created by whsl2014004 on 15/3/31.
//  Copyright (c) 2015年 whsl2014004. All rights reserved.
//

#import "YQQRCode.h"

@implementation YQQRCode

+(UIImage *)enCodeWithString:(NSString *)str withImageSize:(CGFloat)width {
    CIImage *ciimage = [YQQRCode createQRForString:str];
    CGFloat scale = width/ciimage.extent.size.width;
    UIImage *image = [YQQRCode createNonInterpolatedUIImageFromCIImage:ciimage withScale:scale];
    return image;
}


+ (CIImage *)createQRForString:(NSString *)qrString
{
    // Need to convert the string to a UTF-8 encoded NSData object
    NSData *stringData = [qrString dataUsingEncoding:NSUTF8StringEncoding];
    
    // Create the filter
    CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // Set the message content and error-correction level
    [qrFilter setValue:stringData forKey:@"inputMessage"];
    [qrFilter setValue:@"H" forKey:@"inputCorrectionLevel"];
    
    // Send the image back
    return qrFilter.outputImage;
}

+ (UIImage *)createNonInterpolatedUIImageFromCIImage:(CIImage *)image withScale:(CGFloat)scale
{
    // Render the CIImage into a CGImage
    CGImageRef cgImage = [[CIContext contextWithOptions:nil] createCGImage:image fromRect:image.extent];
    
    // Now we'll rescale using CoreGraphics
    UIGraphicsBeginImageContext(CGSizeMake(image.extent.size.width * scale, image.extent.size.width * scale));
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, image.extent.size.height);
    CGContextConcatCTM(context, flipVertical);
    
    // We don't want to interpolate (since we've got a pixel-correct image)
    CGContextSetInterpolationQuality(context, kCGInterpolationNone);
    CGContextDrawImage(context, CGContextGetClipBoundingBox(context), cgImage);
    // Get the image out
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // Tidy up
    UIGraphicsEndImageContext();
    CGImageRelease(cgImage);
    return scaledImage;
}



@end
